﻿using FreeSql;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace WebApiServices.Common {

    public static class DbContextServices {

        public static IServiceCollection AddDbContextServices(this IServiceCollection serviceDescriptors,
            ConfigurationManager configurationManager) {

            string connStr = configurationManager.GetConnectionString("DefaultConnection") ?? "";
            Func<IServiceProvider, IFreeSql> fsqlFactory = r => {
                IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                    .UseConnectionString(FreeSql.DataType.SqlServer, connStr)
                    .UseAdoConnectionPool(true)
                    .UseMonitorCommand(cmd => Debug.WriteLine($"Sql：{cmd.CommandText}"))
                    //.UseAutoSyncStructure(true) //自动同步实体结构到数据库，只有CRUD时才会生成表
                    .Build();
                return fsql;
            };
            serviceDescriptors.AddSingleton<IFreeSql>(fsqlFactory);
            return serviceDescriptors;
        }

    }

}
